package java_thinking.unit_21._21_7;

import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @Desc:   7-2 使用 volatile 类型域来保存取消状态
 * @author: cww
 * @DateTime: 2019/6/13 9:14
 */
@ThreadSafe
public class PrimeGenerator implements Runnable{
    private static ExecutorService exec = Executors.newCachedThreadPool();
    @GuardedBy("this") private final List<BigInteger> primes = new ArrayList<>();
    private volatile boolean cancelled;

    @Override
    public void run() {
        BigInteger p = BigInteger.ONE;
        System.out.println("454545");
        while (!cancelled) {
            p = p.nextProbablePrime();
            System.out.println("fefe");
            synchronized (this) {
                primes.add(p);
            }
        }
    }
    public void cancel() {
        cancelled = true;
    }
    public synchronized List<BigInteger> get() {
        return new ArrayList<>(primes);
    }

    static List<BigInteger> aSecondOfPrimes() throws InterruptedException {
        PrimeGenerator generator = new PrimeGenerator();
        exec.execute(generator);
        try {
            SECONDS.sleep(1);
        } finally {
            //在 finally 中调用 cancel 确保 sleep 被中断也能取消素数生成器的执行
//            generator.cancel();
            PrimeGenerator.exec.shutdownNow();
        }
        return generator.get();
    }

    public static void main(String[] args) throws InterruptedException {
        List<BigInteger> bigIntegers = PrimeGenerator.aSecondOfPrimes();
        System.out.println(bigIntegers);

    }
}
